/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.edu.upc.dai.grupovictor.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pe.edu.upc.dai.grupovictor.model.Ciclo;
import pe.edu.upc.dai.grupovictor.model.Curso;
import pe.edu.upc.dai.grupovictor.model.DetalleSistemaEvaluacion;
import pe.edu.upc.dai.grupovictor.model.SistemaEvaluacion;
import pe.edu.upc.dai.grupovictor.model.TipoEvaluacion;
import pe.edu.upc.dai.grupovictor.service.CicloService;
import pe.edu.upc.dai.grupovictor.service.CursoService;
import pe.edu.upc.dai.grupovictor.service.DetalleSistemaEvaluacionService;
import pe.edu.upc.dai.grupovictor.service.SistemaEvaluacionService;
import pe.edu.upc.dai.grupovictor.service.TipoEvaluacionService;
import pe.edu.upc.dai.grupovictor.service.impl.CicloServiceImpl;
import pe.edu.upc.dai.grupovictor.service.impl.CursoServiceImpl;
import pe.edu.upc.dai.grupovictor.service.impl.DetalleSistemaEvaluacionServiceImpl;
import pe.edu.upc.dai.grupovictor.service.impl.SistemaEvaluacionServiceImpl;
import pe.edu.upc.dai.grupovictor.service.impl.TipoEvaluacionServiceImpl;
import pe.edu.upc.dai.grupovictor.util.json.JSONArray;
import pe.edu.upc.dai.grupovictor.util.json.JSONException;
import pe.edu.upc.dai.grupovictor.util.json.JSONObject;

/**
 *
 * @author daniel
 */
public class AdministradorServlet extends HttpServlet {

    private CicloService cicloService;
    private CursoService cursoService;
    private SistemaEvaluacionService sistemaEvaluacionService;
    private DetalleSistemaEvaluacionService detalleSistemaEvaluacionService;
    private TipoEvaluacionService tipoEvaluacionService;

    public AdministradorServlet() {
        cicloService = new CicloServiceImpl();
        cursoService = new CursoServiceImpl();
        sistemaEvaluacionService = new SistemaEvaluacionServiceImpl();
        detalleSistemaEvaluacionService = new DetalleSistemaEvaluacionServiceImpl();
        tipoEvaluacionService = new TipoEvaluacionServiceImpl();
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {

        String action = request.getParameter("action");

        if ("getCiclos".equalsIgnoreCase(action)) {
            getCiclos(request, response);
        } else if ("getCursos".equalsIgnoreCase(action)) {
            getCursos(request, response);
        } else if ("getSistemaEvaluacionLista".equalsIgnoreCase(action)) {
            getSistemaEvaluacionLista(request, response);
        } else if ("eliminarSistemaEval".equalsIgnoreCase(action)) {
            eliminarSistemaEval(request, response);
        } else if ("addSistemaEval".equalsIgnoreCase(action)) {
            addSistemaEval(request, response);
        } else if ("getDetalle".equalsIgnoreCase(action)) {
            getDetalle(request, response);
        } else if ("getTipoEvalLista".equalsIgnoreCase(action)) {
            getTipoEvalLista(request, response);
        } else if ("saveTipoEvalPorc".equalsIgnoreCase(action)) {
            saveTipoEvalPorc(request, response);
        }


    }

    protected void saveTipoEvalPorc(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        Long idSisEval = Long.valueOf(request.getParameter("idCursoEval"));
        Long idTipoEval = Long.valueOf(request.getParameter("idEvaluacion"));
        Float peso = Float.valueOf(request.getParameter("peso"));

        try {
            DetalleSistemaEvaluacion detalle = new DetalleSistemaEvaluacion();
            detalle.setIdSistemaEvaluacion(new SistemaEvaluacion(idSisEval));
            detalle.setIdTipoEvaluacion(new TipoEvaluacion(idTipoEval));
            detalle.setPesoEvaluacion(peso);

            detalleSistemaEvaluacionService.insertar(detalle);

            jsonObjectRoot.put("message", "Se agregó satisfactoriamente");
            jsonObjectRoot.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObjectRoot.put("success", false);
            jsonObjectRoot.put("message", e.getLocalizedMessage());
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    protected void getTipoEvalLista(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        try {

            List<TipoEvaluacion> list = tipoEvaluacionService.seleccionarTodos();
            JSONArray jsonArray = new JSONArray();
            int i = 0;
            for (TipoEvaluacion item : list) {
                JSONObject jsonObject = new JSONObject(item);
                jsonObject.put("rownum", ++i);
                jsonArray.put(jsonObject);
            }
            jsonObjectRoot.put("data", jsonArray);
            jsonObjectRoot.put("totalCount", list.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    protected void getDetalle(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        Long idCurso = Long.valueOf(request.getParameter("idCurso"));

        try {
            DetalleSistemaEvaluacion filtro = new DetalleSistemaEvaluacion();
            filtro.setIdSistemaEvaluacion(new SistemaEvaluacion(idCurso));

            List<DetalleSistemaEvaluacion> list = detalleSistemaEvaluacionService.seleccionarTodosByPadre(filtro);
            JSONArray jsonArray = new JSONArray();
            int i = 0;
            for (DetalleSistemaEvaluacion item : list) {
                JSONObject jsonObject = new JSONObject(item);

                jsonObject.put("tipoEvaluacion", new JSONObject(item.getIdTipoEvaluacion()));
                jsonObject.put("rownum", ++i);
                jsonArray.put(jsonObject);
            }
            jsonObjectRoot.put("data", jsonArray);
            jsonObjectRoot.put("totalCount", list.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    protected void addSistemaEval(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        Long idCiclo = Long.valueOf(request.getParameter("idCiclo"));
        Long idCurso = Long.valueOf(request.getParameter("idCurso"));

        try {
            SistemaEvaluacion sisEval = new SistemaEvaluacion();
            sisEval.setIdCiclo(new Ciclo(idCiclo));
            sisEval.setIdCurso(new Curso(idCurso));
            sisEval.setEstado("GEN");

            sistemaEvaluacionService.insertar(sisEval);

            jsonObjectRoot.put("message", "Se agrego correctamente");
            jsonObjectRoot.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObjectRoot.put("success", false);
            jsonObjectRoot.put("message", e.getLocalizedMessage());
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    protected void eliminarSistemaEval(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, JSONException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        Long id = Long.valueOf(request.getParameter("idSistemaEvaluacion"));

        try {
            SistemaEvaluacion sisEval = new SistemaEvaluacion(id);
            sistemaEvaluacionService.eliminar(sisEval);

            jsonObjectRoot.put("message", "Se Elimin&oacute; Satisfactoriamente");
            jsonObjectRoot.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonObjectRoot.put("success", false);
            jsonObjectRoot.put("message", e.getLocalizedMessage());
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    protected void getCiclos(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        try {

            List<Ciclo> list = cicloService.seleccionarTodos();
            JSONArray jsonArray = new JSONArray();
            int i = 0;
            for (Ciclo item : list) {
                JSONObject jsonObject = new JSONObject(item);
                jsonObject.put("rownum", ++i);
                jsonArray.put(jsonObject);
            }
            jsonObjectRoot.put("data", jsonArray);
            jsonObjectRoot.put("totalCount", list.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    protected void getCursos(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        try {

            List<Curso> list = cursoService.seleccionarTodos();
            JSONArray jsonArray = new JSONArray();
            int i = 0;
            for (Curso item : list) {
                JSONObject jsonObject = new JSONObject(item);
                jsonObject.put("rownum", ++i);
                jsonArray.put(jsonObject);
            }
            jsonObjectRoot.put("data", jsonArray);
            jsonObjectRoot.put("totalCount", list.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    protected void getSistemaEvaluacionLista(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        JSONObject jsonObjectRoot = new JSONObject();

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        try {

            List<SistemaEvaluacion> list = sistemaEvaluacionService.seleccionarTodos();
            JSONArray jsonArray = new JSONArray();
            int i = 0;
            for (SistemaEvaluacion item : list) {
                JSONObject jsonObject = new JSONObject(item);

                jsonObject.put("curso", new JSONObject(item.getIdCurso()));
                jsonObject.put("ciclo", new JSONObject(item.getIdCiclo()));

                jsonObject.put("rownum", ++i);
                jsonArray.put(jsonObject);
            }
            jsonObjectRoot.put("data", jsonArray);
            jsonObjectRoot.put("totalCount", list.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.print(jsonObjectRoot.toString());
            out.flush();
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
